<template>
	<div>
		<!-- 为表格添加垂直和水平滚动容器，高度自适应浏览器高度 -->
		<div style="overflow: auto; width: 100%; height: calc(100vh - 100px);">
			<el-table :data="tableData" border :span-method="objectSpanMethod" :row-class-name="tableRowClassName"
				style="min-width: 1000px;">
				<!-- <el-table-column label="城市" prop="cityName"></el-table-column> -->
				<!-- 动态生成代理商层级列 -->
				<template v-for="level in maxAgentLevel" :key="level">
					<el-table-column :label="`${level}级代理商`" :prop="`level-${level}`">
						<template #default="{ row }">
							{{ row[`level-${level}`] || '' }}
						</template>
					</el-table-column>
				</template>
				<el-table-column label="门店" prop="shopName"></el-table-column>
				<el-table-column label="订单数" prop="orderCount"></el-table-column>
				<el-table-column label="金额" prop="totalAmount"></el-table-column>
			</el-table>
		</div>
	</div>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'appointment-board'
});

import { useCool } from '/@/cool';
import { onMounted, ref, watch, computed } from 'vue';
import dayjs from 'dayjs';

const { service } = useCool();

// 定义数据类型接口
export interface ShopData {
	cityName: string;
	cityId?: number;
	shopName: string;
	shopId?: number;
	orderCount: number;
	amount: number;
	isTotal?: boolean;
	isCityTotal?: boolean;
	isAgentTotal?: boolean;
	// 存储各级代理商信息
	agentLevel?: number;
	// 代理商层级名称数组
	agentNames?: string[];
	// 代理商层级ID数组
	agentUserIds?: number[];
}

const tableData = ref<ShopData[]>([]);
const cityId = ref('');
const shopId = ref('');
const appointmentTime = ref([
	dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
	dayjs().format('YYYY-MM-DD')
]);
// 最大代理商层级
const maxAgentLevel = ref(0);

// 监听城市变化
watch(cityId, () => {
	getData();
});

// 监听门店变化
watch(shopId, () => {
	getData();
});

onMounted(async () => {
	getSelection();
	getData();
});

const cityList = ref([]);
const shopList = ref([]);

// 获取数据
async function getData() {
	const params = {
		cityId: cityId.value,
		shopId: shopId.value,
		isAgent: true
	};

	// const res: Record<string, any> = await service.order.city.tongkangShopBoard(params)
	const res: Record<string, any> = await service.agent.agent.agentBoard(params);
	if (res) {
		const rawData = res.tableData || [];
		maxAgentLevel.value = res.maxAgentLevel || 0;

		// 如果存在1级代理商，添加合计行
		if (maxAgentLevel.value >= 1) {
			// 根据1级代理商分组
			const level1Groups = new Map();

			// 遍历数据进行分组
			for (const row of rawData) {
				const level1Agent = row['level-1'];
				if (level1Agent) {
					if (!level1Groups.has(level1Agent)) {
						level1Groups.set(level1Agent, []);
					}
					level1Groups.get(level1Agent).push(row);
				}
			}

			// 构建包含合计行的新数据
			const newTableData = [];

			// 处理每个1级代理商组
			for (const [agentName, agentRows] of level1Groups.entries()) {
				// 添加该代理商的所有数据行
				newTableData.push(...agentRows);

				// 计算合计值
				let totalOrders = 0;
				let totalAmount = 0;

				for (const row of agentRows) {
					totalOrders += row.orderCount || 0;
					totalAmount += row.totalAmount || 0;
				}

				// 创建合计行
				const totalRow: ShopData = {
					cityName: '',
					shopName: '合计',
					orderCount: totalOrders,
					totalAmount: totalAmount,
					isAgentTotal: true
				};

				// 设置各级代理商信息
				// for (let level = 1; level <= maxAgentLevel.value; level++) {
				// 	totalRow[`level-${level}`] = level === 1 ? agentName : '';
				// }

				// 添加合计行
				newTableData.push(totalRow);
			}

			// 添加没有1级代理商的数据行
			const noLevel1Rows = rawData.filter(row => !row['level-1']);
			newTableData.push(...noLevel1Rows);

			tableData.value = newTableData;
		} else {
			// 没有1级代理商时，直接使用原始数据
			tableData.value = rawData;
		}
	}
}

// 表格行样式函数
function tableRowClassName({ row }) {
	// 如果是合计行，返回total-row类名
	if (row.isAgentTotal) {
		return 'total-row';
	}
	return '';
}

// 合并单元格方法
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
	// 如果是合计行，不进行合并
	if (row.isAgentTotal) {
		return { rowspan: 1, colspan: 1 };
	}

	// 只处理代理商列（列索引0到maxAgentLevel-1）
	if (columnIndex >= 0 && columnIndex < maxAgentLevel.value) {
		const level = columnIndex + 1;
		const currentAgent = row[`level-${level}`];

		// 如果当前代理商为空，不合并
		if (!currentAgent) {
			return { rowspan: 1, colspan: 1 };
		}

		// 检查上一行是否有相同的代理商
		if (rowIndex > 0) {
			const prevRow = tableData.value[rowIndex - 1];
			// 如果上一行是合计行或者代理商不同，则不合并
			if (prevRow.isAgentTotal || prevRow[`level-${level}`] !== currentAgent) {
				// 开始新的合并
				let rowspan = 1;
				for (let i = rowIndex + 1; i < tableData.value.length; i++) {
					const nextRow = tableData.value[i];
					// 如果遇到合计行或代理商不同，则停止合并
					if (nextRow.isAgentTotal || nextRow[`level-${level}`] !== currentAgent) {
						break;
					}
					rowspan++;
				}
				return { rowspan, colspan: 1 };
			} else {
				// 与上一行相同，被合并
				return { rowspan: 0, colspan: 0 };
			}
		} else {
			// 第一行，开始新的合并
			let rowspan = 1;
			for (let i = rowIndex + 1; i < tableData.value.length; i++) {
				const nextRow = tableData.value[i];
				// 如果遇到合计行或代理商不同，则停止合并
				if (nextRow.isAgentTotal || nextRow[`level-${level}`] !== currentAgent) {
					break;
				}
				rowspan++;
			}
			return { rowspan, colspan: 1 };
		}
	}

	// 其他列不合并
	return { rowspan: 1, colspan: 1 };
}
</script>

<style scoped>
:deep(.el-table .total-row) {
	background-color: #edeff1;
	font-weight: bold;
}
</style>
